﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.WindowsAzure.StorageClient;

using Canyala.Lagoon.Models;

namespace Canyala.Lagoon.Entities
{
    public class AuthorizationTicket : TableServiceEntity
    {
        /// <summary>
        /// Date and time when this ticket was issued (i.e first valid).
        /// </summary>
        public DateTime Issued { get; set; }

        /// <summary>
        /// Guid identity for the UserAccount tied with this ticket.
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// The name of the UserAccount tied with this account ("admin" or "john.doe").
        /// </summary>
        public string User { get; set; }

        /// <summary>
        /// Creates a new authorization based on a user account
        /// </summary>
        /// <param name="userAccount">The user account</param>
        /// <returns>The new authorization</returns>
        public static AuthorizationTicket FromUserAccount(UserAccount userAccount)
        { 
            return new AuthorizationTicket
            {
                PartitionKey = userAccount.PartitionKey,
                RowKey = Guid.NewGuid().ToString(),
                User = userAccount.RowKey,
                UserId = userAccount.Id,
                Issued = DateTime.UtcNow
            };
        }

        /// <summary>
        /// Creates a new authorization based on an old authorization
        /// </summary>
        /// <param name="authorization">The old authorization</param>
        /// <returns>The new authorization</returns>
        public static AuthorizationTicket FromAuthorization(AuthorizationTicket authorization)
        {
            return new AuthorizationTicket
            {
                PartitionKey = authorization.PartitionKey,
                RowKey = Guid.NewGuid().ToString(),
                UserId = authorization.UserId,
                User = authorization.User,
                Issued = DateTime.UtcNow
            };
        }

        public bool HasExpired()
            { return (DateTime.UtcNow - Issued) > TimeSpan.FromMinutes(5);  }

        public string AsTicket()
            { return String.Concat(RowKey, "@", PartitionKey); }
    }
}
